﻿//using DAL;
using DAL3;
//using LabelManager;
using LabelManager2;
using Newtonsoft.Json;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace GEMINI_OP130
{
    public partial class FormMain : Form
    {
        private ScanerHook listener = new ScanerHook();
        public string str = "未连接";
        string strs = "";
        int PLC_Count = 1;
        Socket socketSend;
        public string server = "";
        public static string[] typeArray = new string[150];
        string[] EMArray = new string[150];
        string[] saoma = new string[2];
        public string[] alarmNum = new string[20];     //用于读取报警显示
        public bool clear;          //用于清除报警显示
        string icID;
        string result;
        //string unqualifiednumber;   //用于记录不合格工位号
        string Fxnumber;       //用于读取返修次数
        string day;         //存储DIDI日期排序
        char[] DIDIday = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
        public bool read;
        int num1;
        bool save;
        string neirong;
        private string[] stepNum = new string[20];
        public struct print
        {
            public static string lingjianhao;
            public static string banbenhao;
            public static string AIdaima;
            public static string chanxianbanci;
            public static string biaoqianmuban;
        }

        public struct plcStructIn
        {
            public bool bool_0;
            public bool bool_1;
            public bool bool_2;
            public bool bool_3;
            public bool bool_4;
            public bool bool_5;
            public bool bool_6;
            public bool bool_7;

            public byte byte_0;
            public byte byte_1;
            public byte byte_2;//生产型号
            public byte byte_3;
            public byte byte_4;
            public byte byte_5;

            public Int16 int_0;
            public Int16 int_1;
            public Int16 int_2;
            public Int16 int_3;
            public Int16 int_4;
            public Int16 int_5;
            public Int16 int_6;
            public Int16 int_7;

            public UInt32 Uint_0;//序列号

        }
        //----线程循环
        bool _Continue = true;
        //----PLC监控线程数组
        Thread[] PLC_Td;
        //PLC实例数组
        public static SimenesPLC[] PLC_Link;
        //PLC DB结构数组
        public plcStructIn[] Struct_Test;
        public static plcStructIn _plcStruct = new plcStructIn();

        public static FormMain FM10;
        public FormMain()
        {
            InitializeComponent();
            FM10 = (FormMain)this;
            printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.LotteryPrintPage);
            listener.ScanerEvent += Listener_ScanerEvent;
        }
        /// <summary>
        /// 打开窗体，将页面嵌入到主窗体
        /// </summary>
        /// <param name="form"></param>
        private void OpenForm(Form form)
        {
            //将当前子窗体设置成非顶级控件
            form.TopLevel = false;
            //设置窗体最大化
            form.WindowState = FormWindowState.Maximized;
            //设置窗体无边框
            form.FormBorderStyle = FormBorderStyle.None;
            //设置窗体嵌入容器
            form.Parent = this.panel1;
            form.Show();
        }
        /// <summary>
        /// 关闭窗体，将容器内窗体移除
        /// </summary>
        private void CloseForm()
        {
            //遍历这个容器里面的所有控件，找出窗体对象
            foreach (Control item in this.panel1.Controls)
            {
                if (item is Form)
                {
                    Form form = (Form)item;
                    form.Close();
                    //移除
                    this.panel1.Controls.Remove(item);
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //嵌入窗口
            //this.CloseForm();
            FormUserLoginInterface formUserLoginInterface = new FormUserLoginInterface();
            //this.OpenForm(formUserLoginInterface);
            formUserLoginInterface.Show();
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            listener.Stop();
            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 260, 4, 0);
            //关闭主窗体时释放后台线程的资源
            for (int I = 0; I < PLC_Count; I++)
            {
                if (PLC_Td[I] != null)
                {
                    PLC_Td[I].Abort();
                }
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            //取消跨线程的访问
            Control.CheckForIllegalCrossThreadCalls = false;
            #region 连接PLC
            PLC_Td = new Thread[PLC_Count];
            PLC_Link = new SimenesPLC[PLC_Count];
            Struct_Test = new plcStructIn[PLC_Count];
            for (int I = 0; I < PLC_Count; I++)
            {
                PLC_Td[I] = new Thread(PLC_Td_Func);
                PLC_Td[I].IsBackground = true;
                PLC_Td[I].Start(I);
            }
            #endregion
            timer.Enabled = true;
            timer.AutoReset = true;
            timer.Interval = 1000;
            timer.AutoReset = false;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timercall.Enabled = true;
            timercall.AutoReset = true;
            timercall.Interval = 1000;
            timercall.AutoReset = false;
            timercall.Elapsed += new System.Timers.ElapsedEventHandler(timercall_Elapsed);
            #region 与服务器tcp/ip通讯建立连接
            try
            {
                //创建负责通信的Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse("172.16.150.1");
                IPEndPoint point = new IPEndPoint(ip, 50001);
                //获得要连接的远程服务器应用程序的IP地址和端口号
                socketSend.Connect(point);
                server = "成功";

                //开启一个新的线程不停的接收服务端发来的消息
                Thread th = new Thread(Recive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {
                server = "失败";
            }
            #endregion

            #region 向服务器获取所有产品型号
            string sql = "select [typeName] from parameterSetting";
            SqlDataReader objReader = SQLHelp.GetReader(sql);
            int temp2 = 0;
            while (objReader.Read())
            {
                //EMArray[temp2] = objReader["OP10扫码"].ToString();
                typeArray[temp2] = objReader["typeName"].ToString();
                comboBox1.Items.Add(typeArray[temp2]);

                temp2 += 1;
            }
            objReader.Close();
            #endregion

            #region 设置串口参数并打开串口接收
            //波特率

            //IC卡
            //serialPort1.BaudRate = 9600;
            //扫码
            serialPort2.BaudRate = 115200;

            //数据位

            //IC卡
            //serialPort1.DataBits = 8;
            //扫码
            serialPort2.DataBits = 8;

            //奇偶校验位
            //serialPort1.Parity = System.IO.Ports.Parity.None;
            serialPort2.Parity = System.IO.Ports.Parity.None;

            //停止位
            //serialPort1.StopBits = System.IO.Ports.StopBits.One;
            serialPort2.StopBits = System.IO.Ports.StopBits.One;

            string[] contents = new string[2];
            try
            {
                contents = File.ReadAllLines(System.Windows.Forms.Application.StartupPath + "\\COM口配置.txt", Encoding.UTF8);
            }
            catch
            {
                label28.Text += "请检查COM口配置！";
            }
            //端口
            //try
            //{
            //    serialPort1.PortName = contents[0];
            //    serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
            //    serialPort1.Open();

            //}
            //catch
            //{
            //    MessageBox.Show("IC卡端口打开失败，请检查串口连接是否正确！", "错误提示");
            //}

            try
            {
                serialPort2.PortName = contents[1];
                serialPort2.DataReceived += new SerialDataReceivedEventHandler(SerialPort2_DataReceived);
                serialPort2.Open();
            }
            catch
            {
                MessageBox.Show("扫码端口打开失败，请检查串口连接是否正确！", "错误提示");
            }
            #endregion
            
            listener.Start();
            
        }
        string ID = "";
        //PLC线程
        private void PLC_Td_Func(object ob)
        {
            Ping p = new Ping();
            int num = (int)ob;

            string[] PLC_IP = new string[PLC_Count];
            PLC_IP[0] = "172.16.1.2";
            PLC_Link[num] = new SimenesPLC(CpuType.S71200, PLC_IP[num].ToString(), 0, 1);
            while (_Continue)
            {
                try
                {
                    //处理相应的PLC对象的数据处理
                    if (p.Send(PLC_IP[num], 200).Status == IPStatus.Success)//如果200ms时间间隔ping通了
                    {
                        if (PLC_Link[num].plc.IsConnected == false)//plc没有连接上
                        {
                            //int s = (int)PLC_Link[num].plc.Open();
                            //strs = Convert.ToString(s);
                            //if (s == 0)
                            //{
                            //    str = "成功";
                            //    SimenesPLC.conectStatus = true;
                            //}
                            //else
                            //{
                            //    str = "失败";
                            //    SimenesPLC.conectStatus = false;
                            //}
                            try
                            {
                                PLC_Link[0].plc.Open();
                                SimenesPLC.conectStatus = true;
                                str = "成功";
                            }
                            catch (Exception)
                            {
                                SimenesPLC.conectStatus = false;
                                str = "失败";
                                //throw;
                            }
                        }
                        else
                        { 
                            str = "成功";
                            //读取DB
                            Struct_Test[num] = (plcStructIn)PLC_Link[num].plc.ReadStruct(typeof(plcStructIn), 99, 532);
                            _plcStruct = Struct_Test[num];
                            ID = PLC_Link[num].plc.Read(DataType.DataBlock, 99, 556, VarType.DInt, 1).ToString();

                            if (ID != "" && !read)
                            {
                                day = DIDIday[int.Parse(System.DateTime.Now.ToString("yy")) - 18].ToString();
                                day += DIDIday[int.Parse(System.DateTime.Now.ToString("MM")) + 8].ToString();
                                day += DIDIday[int.Parse(System.DateTime.Now.ToString("dd")) - 1].ToString();
                               
                                read = true;
                            }
                            if ((Byte)PLC_Link[num].plc.Read(DataType.DataBlock, 99, 2, VarType.Byte, 1) > 0)
                            {
                                #region 向服务器获取所有产品型号
                                label28.Text = "向服务器获取所有产品型号";
                                string sql = "select [typeName] from parameterSetting";
                                SqlDataReader objReader = SQLHelp.GetReader(sql);
                                int temp2 = 0;
                                while (objReader.Read())
                                {
                                    //EMArray[temp2] = objReader["OP10扫码"].ToString();
                                    typeArray[temp2] = objReader["typeName"].ToString();
                                    comboBox1.Items.Add(typeArray[temp2]);
                                    temp2 += 1;
                                }
                                objReader.Close();
                                #endregion
                            }

                            yesterday = File.ReadAllText(@"D:\yesterday.txt");
                            yesterday = JsonConvert.DeserializeObject<string>(yesterday);
                            if (yesterday != System.DateTime.Now.ToString("yyMMdd"))
                            {
                                PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, 1);
                                PLC_Link[0].plc.Write(DataType.DataBlock, 101, 4, 1);
                                strfile = JsonConvert.SerializeObject(System.DateTime.Now.ToString("yyMMdd"));
                                File.WriteAllText("d:\\yesterday.txt", strfile);
                            }
                            else
                            {

                            }

                            if ((Byte)PLC_Link[num].plc.Read(DataType.DataBlock, 99, 509, VarType.Byte, 1) > 0)     //Byte：DB99.509,不合格工位号
                            {
                                label28.Text = "进入不合格标签打印";
                                if (printBok == false)
                                {
                                    //unqualifiednumber = "OP" + (Byte)PLC_Link[num].plc.Read(DataType.DataBlock, 99, 537, VarType.Byte, 1)/*_plcStruct.byte_4*/;
                                    label28.Text = "可以打印";
                                    NGprintLab(@"D:\printNG\DIDI不合格标签.lab", "NG print", "OP" + (Byte)PLC_Link[num].plc.Read(DataType.DataBlock, 99, 509, VarType.Byte, 1)/*_plcStruct.byte_4*/ + "不合格：" /*+ ng.Replace("rn", "\r\n")*/);        //23/11/15 OK与NG互换先生产使用,已改回，待验证
                                    //printLab(@"D:\print\" + "DIDI不合格标签.lab", "ZDesigner ZT411-300dpi ZPL (副本 2)");
                                    printDoc.DefaultPageSettings.PrinterSettings.PrinterName = "NG print";
                                    //PLC_Link[num].plc.Write(DataType.DataBlock, 99, 509,/* VarType.Byte,*/ 0);
                                    printBok = true;
                                }
                            }
                            else
                            {
                                printBok = false;
                            }
                            try
                            {
                                //string sql = "select [产品系列号] from parameterSetting where typeName = '{0}'";
                                string sql = "select [row] from parameterSetting where typeName = '{0}'";
                                sql = string.Format(sql, label2.Text);
                                SqlDataReader objReader1 = SQLHelp.GetReader(sql);
                                while (objReader1.Read())
                                {
                                    //typeNameTemp = Convert.ToInt32(objReader1["产品系列号"]) + 1;
                                    typeNameTemp = Convert.ToInt32(objReader1["row"]);

                                }
                                objReader1.Close();

                                pictureBox3.Image = System.Drawing.Image.FromFile(System.Windows.Forms.Application.StartupPath + @"\SOP\" + typeNameTemp + ".png");
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                            #region  报警记录
                            //报警记录
                            if (_plcStruct.bool_5)
                            {
                                //inAlarm("OA报警[1]夹紧气缸前进超时A");            

                            }
                            else if (_plcStruct.bool_5)
                            {
                                //inAlarm("OA报警[2]夹紧气缸返回超时A");
                            }
                            else if (_plcStruct.bool_5)
                            {
                                //inAlarm("OA报警[3]推进1前进超时A");
                            }
                            else if (_plcStruct.bool_5)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_5)
                            {
                                //inAlarm("OA报警[5]推进2前进超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[6]推进2返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_6)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_7)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_7)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_7)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_7)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }
                            else if (_plcStruct.bool_7)
                            {
                                //inAlarm("OA报警[4]推进1返回超时A");
                            }

                            #endregion
                            //型号
                            if (_plcStruct.byte_2 > 0)
                            {
                                label2.Text = typeArray[_plcStruct.byte_2 - 1];
                            }
                            //托盘号
                            label5.Text = _plcStruct.byte_3.ToString();
                            //测试时间
                            label7.Text = _plcStruct.int_5 / 60 + "分" + _plcStruct.int_5 % 60 + "秒";
                            //计划生产数
                            label9.Text = _plcStruct.int_0.ToString();
                            //当前生产数
                            label11.Text = _plcStruct.int_1.ToString();
                            //合格数
                            label13.Text = _plcStruct.int_2.ToString();
                            //不合格数
                            label15.Text = _plcStruct.int_3.ToString();
                            //复测数
                            //label17.Text = _plcStruct.int_4.ToString();
                            //呼叫系统
                            if (Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 6)))
                            {
                                button7.BackColor = Color.Green;
                            }
                            else
                            {
                                button7.BackColor = Color.Aquamarine;
                            }
                            if (Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 7)))
                            {
                                button8.BackColor = Color.Green;
                            }
                            else
                            {
                                button8.BackColor = Color.Aquamarine;
                            }
                            //步骤提示
                            try
                            {
                                stepNum = File.ReadAllLines(System.Windows.Forms.Application.StartupPath + "\\步骤配置.txt", Encoding.UTF8);
                                label51.Text = stepNum[PLC_Link[0].readInt("DB10050.DBW90.0")];
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                            //总结果判断
                            if (_plcStruct.bool_5)  //DB99.532.5出OK标签
                            {
                                result = "合格";
                                label26.Text = "合格";
                                label26.BackColor = System.Drawing.Color.Green;
                                if (printAok == false)
                                {

                                    #region 向服务器获取打印内容
                                    label28.Text = "向服务器获取打印内容";
                                    string sql = "select [零件号],[版本号],[AI代码号],[产线班次号],[打印模板名称] from parameterSetting where [typeName] = " + "'" + label2.Text + "'";
                                    SqlDataReader objReader = SQLHelp.GetReader(sql);

                                    while (objReader.Read())
                                    {
                                        print.lingjianhao = objReader["零件号"].ToString();
                                        print.banbenhao = objReader["版本号"].ToString();
                                        print.AIdaima = objReader["AI代码号"].ToString();
                                        print.chanxianbanci = objReader["产线班次号"].ToString();
                                        print.biaoqianmuban = objReader["打印模板名称"].ToString();
                                    }
                                    objReader.Close();
                                    #endregion

                                    printLab(@"D:\print\" + print.biaoqianmuban, "OK print");       //23/11/15 OK与NG互换先生产使用,已改回，待验证
                                    printA = true;
                                    this.printDoc.Print();
                                }

                            }
                            else if (_plcStruct.bool_6)     //DB99.532.6出NG标签
                            {
                                result = "不合格";
                                label26.Text = "不合格";
                                label26.BackColor = System.Drawing.Color.Red;
                                if (printCok == false)
                                {
                                    NGprintLab(@"D:\printNG\DIDI不合格标签.lab", "NG print", "OP100人工判断不合格：" );
                                    //printLab(@"D:\printNG\DIDI不合格标签.lab", "ZDesigner ZT411-300dpi ZPL");
                                    //printDoc.DefaultPageSettings.PrinterSettings.PrinterName = "ZDesigner ZT411-300dpi ZPL (副本 1)";
                                    printCok = true;
                                }

                            }
                            else
                            {
                                result = "未测试";
                                label26.Text = "未测试";
                                label26.BackColor = System.Drawing.Color.Silver;
                                if (save/*|| (bool)PLC_Link[0].plc.Read(DataType.DataBlock, 10050, 1, VarType.Bit, 1, 1)*/)   //DB10050.DBX1.1 返回原位
                                {
                                    PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 0, 0);    //DB99.240.0 扫码OK
                                    PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 1, 0);    //DB99.240.1 扫码NG
                                    textBox9.Text = "";
                                    textBox9.BackColor = System.Drawing.Color.Silver;
                                    read = false;

                                }
                                PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 2, 0);    //DB99.240.2 数据传输完成信号
                                printAok = false;
                                printCok = false;
                                textBox9.Text = "";
                                textBox9.BackColor = System.Drawing.Color.Silver;
                                //unqualifiednumber = "";
                                save = false;
                            }
                            if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX28.0"))     //顶升气缸伸出到位
                            {
                                //unqualifiednumber = "OP" + (Byte)PLC_Link[num].plc.Read(DataType.DataBlock, 99, 537, VarType.Byte, 1)/*_plcStruct.byte_4*/;
                                if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX93.0"))     //OP70合格否？
                                {
                                    label17.Visible = false;
                                }
                                else
                                {
                                    label17.Visible = true;
                                }
                                if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX93.1"))       //OP80合格否？
                                {
                                    label20.Visible = false;
                                }
                                else
                                {
                                    label20.Visible = true;
                                }
                                if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX93.2"))       //OP90合格否？
                                {
                                    label22.Visible = false;
                                }
                                else
                                {
                                    label22.Visible = true;
                                }
                            }
                            else if (!FormMain.PLC_Link[0].readBoolen("DB10050.DBX28.0"))
                            {
                                label17.Visible = false;
                                label20.Visible = false;
                                label22.Visible = false;
                            }
                            else
                            {
                                label28.Text = "程序异常";
                            }

                            //数据记录
                            //proData.operatorter = Program.userlogin.Admin;//操作员
                            label39.Text = Program.userlogin.Admin;
                            label40.Text = Program.userlogin.serialNumber.ToString();
                            if (Program.userlogin.Admin != "")
                            {
                                PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 4, 1);
                            }
                            else
                            {
                                PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 4, 0);
                            }
                            label38.BackColor = _plcStruct.bool_4 ? Color.Green : Color.Red;
                            label41.BackColor = save ? Color.Red : Color.Green;
                            label42.BackColor = (bool)PLC_Link[0].plc.Read(DataType.DataBlock, 99, 240, VarType.Bit, 1, 2) ? Color.Red : Color.Green;
                            if (_plcStruct.bool_4/*DB99.532.4 过程完成*/ && save == false && (bool)PLC_Link[0].plc.Read(DataType.DataBlock, 99, 240, VarType.Bit, 1, 2) == false)    //DB99.240.2，数据记录完成
                            {
                                FileStream fs = new FileStream("日志.txt", FileMode.Append);
                                StreamWriter sw = new StreamWriter(fs);

                                label28.Text = "开始记录数据";
                                sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "开始记录数据");
                                //历史记录
                                string sql = "update productData set [OP100人工判定结果] = '{0}',[OP100结果] = '{0}',[OP100操作员] = '{1}',[产品下线时间] = '{2}',[OP100操作时间] = '{3}',[总成码] = '{4}',[总结果] = '{5}' where [ID] = '{6}'";     //未记录数据。
                                //sql = string.Format(sql, result, Program.userlogin.Admin, System.DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"), label7.Text, result.Contains("不合格") ? "OP" + _plcStruct.byte_4 + "0" : textBox9.Text, label26.Text, ID);         //DB99.532
                                sql = string.Format(sql, result, Program.userlogin.Admin, System.DateTime.Now.ToString("yyyy/MM/dd") + " " + label19.Text, label7.Text, result.Contains("不合格") ? "OP100" : result.Contains("未测试") ? /*unqualifiednumber*/"OP" + _plcStruct.byte_4 : textBox9.Text, label26.Text, ID);
                                try
                                {
                                    num1 = SQLHelp.AddData(sql);
                                    if (num1 > 0)
                                    {
                                        PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 2, 1);
                                        //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 260, 0, 0);
                                        //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 260, 1, 0);
                                    }
                                    save = true;
                                    label28.Text = "数据记录完成";
                                    sw.WriteLine(System.DateTime.Now + "-" + ID + "总成码" + (result.Contains("不合格") ? "OP" + _plcStruct.byte_4 + "0" : textBox9.Text));
                                    sw.WriteLine(System.DateTime.Now + "-" + ID + "总结果" + label26.Text);
                                    sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "数据记录完成");
                                    sw.Close();
                                    fs.Close();
                                }
                                catch (Exception)
                                {
                                    throw;

                                }

                            }
                        }
                    }
                    else
                    {
                        //PLC_Link[num].plc.Close();
                        str = "ping失败";
                    }
                    if (p.Send("172.16.150.1", 200).Status == IPStatus.Success)
                    {
                        server = "成功";
                    }
                    else
                    {
                        server = "ping失败";
                    }
                }
                catch (Exception ex1)
                {
                    //str = "出现异常";
                    MessageBox.Show(Convert.ToString(ex1), "错误提示!");
                }

                if (str.Equals("成功"))
                {
                    label29.BackColor = System.Drawing.Color.Green;
                }
                else
                {
                    label29.BackColor = System.Drawing.Color.Red;
                }
                if (server.Equals("成功"))
                {
                    label30.BackColor = System.Drawing.Color.Green;
                }
                else
                {
                    label29.BackColor = System.Drawing.Color.Red;
                }
                Thread.Sleep(100);
                if (label242.Text == "")
                {
                    label242.Text = "使用公司：空调国际(上海)有限公司   \t 设备公司：重庆英之拓智能设备有限公司  \t  软件版本号：V2.0";
                    label242.Text = string.Format(label242.Text, Program.userlogin.name);
                }
                else
                {

                }
            }

        }
        int typeNameTemp = 0;   //用于SOP显示
        /// <summary>
        /// 不停的接受服务器发来的消息
        /// </summary>
        void Recive()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    int r = socketSend.Receive(buffer);
                    //实际接收到的有效字节数
                    if (r == 0)
                    {
                        break;
                    }
                    //表示发送的字符消息,并且是所有产品型号
                    if (buffer[0] == 0)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r - 1);

                        //0 5 ,aaa,asas,dsds,gfhh,hhggh,
                        //截取所有型号
                        typeArray = s.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    }
                    //表示发送的字符消息,并且是扫码参数
                    if (buffer[0] == 1)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        //1,hhggh
                        //截取扫码参数设置
                        saoma = s.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    }
                    //else if (buffer[0] == 1)
                    //{
                    //    SaveFileDialog sfd = new SaveFileDialog();
                    //    sfd.InitialDirectory = @"C:\Users\SpringRain\Desktop";
                    //    sfd.Title = "请选择要保存的文件";
                    //    sfd.Filter = "所有文件|*.*";
                    //    sfd.ShowDialog(this);
                    //    string path = sfd.FileName;
                    //    using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                    //    {
                    //        fsWrite.Write(buffer, 1, r - 1);
                    //    }
                    //    MessageBox.Show("保存成功");
                    //}
                    //else if (buffer[0] == 2)
                    //{
                    //    ZD();
                    //}

                }
                catch { }

            }
        }

        //IC卡

        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {

                Thread.Sleep(50);
                byte[] byteRead1 = new byte[serialPort1.BytesToRead];
                serialPort1.Read(byteRead1, 0, byteRead1.Length);
                byte[] temp6 = new byte[1];
                temp6[0] = byteRead1[20];
                icID = byteToHexStr(temp6, 1);
                Program.userlogin = UserManagement.GetUser(Convert.ToInt32(icID));
                label242.Text = "当前登录用户：{0} \t\t  使用公司：空调国际(上海)有限公司   \t 设备公司：重庆英之拓智能设备有限公司  \t  软件版本号：V1.0";
                label242.Text = string.Format(label242.Text, Program.userlogin.name);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc + "接收失败");
            }

        }
        //扫码枪
        private void SerialPort2_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(100);
                byte[] byteRead = new byte[serialPort2.BytesToRead];
                serialPort2.Read(byteRead, 0, byteRead.Length);
                string indata = Encoding.UTF8.GetString(byteRead);
                textBox9.Text = indata;

                if ((!indata.Contains("D01") && (label2.Text == "DIDI")) || PLC_Link[0].readBoolen("DB99.DBX240.5"))       //DB99.DBX240.5打印合格标签，持续给
                {
                    #region 查询总成码是否重复
                    string sql = "select [总成码] from productData where [总成码] = '" + textBox9.Text + "'";
                    SqlDataReader objReader = SQLHelp.GetReader(sql);
                    int temp2 = 0;
                    while (objReader.Read())
                    {
                        temp2 = 1;
                        label28.Text = "条码重复";
                    }
                    objReader.Close();
                    #endregion
                    //label23.Text = neirong;
                    if (textBox9.Text.Equals(neirong) && temp2 == 0 && ((textBox9.Text.Contains("81051") && label2.Text =="DIDI") || ((textBox9.Text.Contains("RT6") && label2.Text.Contains("百度"))) && temp.Length == 5))
                    {
                        label28.Text = textBox9.Text.Length.ToString();
                        textBox9.BackColor = System.Drawing.Color.Green;
                        PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 0, 1);

                    }
                    else
                    {
                        textBox9.BackColor = System.Drawing.Color.Red;
                        PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 1, 1);
                        if (textBox9.Text.Length != 40)
                        {
                            label28.Text = "条码位数不正确,请点击合格标签单张打印按钮！";
                        }
                    }
                }
                else if((indata.Contains("DIDI"))|| (indata.Contains("D01")) || (((label2.Text == "百度前空调")/* && indata.Contains("")*/) || ((label2.Text == "百度后空调")/* && indata.Contains("")*/)))
                {
                    textBox9.BackColor = System.Drawing.Color.White;
                    #region 查询内部码
                    string sql = "select [内部码], [返修次数] from productData where [ID] = '" + ID + "'";
                    SqlDataReader objReader = SQLHelp.GetReader(sql);

                    while (objReader.Read())
                    {
                        label28.Text = objReader["内部码"].ToString();
                        Fxnumber = objReader["返修次数"].ToString();
                        if (objReader["内部码"].ToString().Contains(indata))
                        {
                            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 5, 1); //托盘对应产品与托盘上的产品能够对应上，给PLC一个信号 DB99.240.5
                            textBox9.BackColor = System.Drawing.Color.Green;
                        }
                    }
                    objReader.Close();
                    if (textBox9.BackColor != System.Drawing.Color.Green)
                    {
                        textBox9.BackColor = System.Drawing.Color.Red;
                    }
                    #endregion
                }
                else
                {
                    label28.Text = "扫码逻辑判断出错";
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc + "接收失败");
            }

        }
        public string byteToHexStr(byte[] bytes, int len)  //数组转十六进制字符
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < len; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        private static byte[] strToToHexByte(string hexString) //字符串转16进制
        {
            //hexString = hexString.Replace(" ", " "); 
            if ((hexString.Length % 2) != 0)
                hexString = "0" + hexString;
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        //计数清零
        private void button2_MouseDown(object sender, MouseEventArgs e)
        {
            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 3, 1);
            //GetDayNumberOfYear();
        }

        private void button2_MouseUp(object sender, MouseEventArgs e)
        {
            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 3, 0);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label18.Text = System.DateTime.Now.ToString("yyyy/MM/dd");
            label19.Text = System.DateTime.Now.ToLongTimeString();
            //状态
            if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX1.2"))
            {
                button5.BackColor = Color.Green;   //报警复位
            }
            else
            {
                button5.BackColor = Color.Silver;
            }
            if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX1.1"))
            {
                button13.BackColor = Color.Green;   //返回原位（大复位）
            }
            else
            {
                button13.BackColor = Color.Silver;
            }
            if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX24.0"))
            {
                button6.BackColor = Color.Green;   //自动模式
            }
            else
            {
                button6.BackColor = Color.Silver;
            }
            if (FormMain.PLC_Link[0].readBoolen("DB10050.DBX24.1"))
            {
                button12.BackColor = Color.Green;   //手动模式
            }
            else
            {
                button12.BackColor = Color.Silver;
            }
            //PLC点位报警，未验证。
            //报警
            try
            {
                if (PLC_Link[0].ReadByte(DataType.DataBlock, 10080, 2) > 0)
                {
                    alarmNum = File.ReadAllLines(System.Windows.Forms.Application.StartupPath + "\\报警配置.txt", Encoding.UTF8);
                    for (int i = 0; i < 8; i++)
                    {
                        if (PLC_Link[0].readBoolen("DB10080.DBX2." + i.ToString()))
                        {
                            //inAlarm("OA报警[1]夹紧气缸前进超时A"); 
                            label242.Text = alarmNum[i];
                            clear = true;
                            break;
                        }
                    }
                }
                //else if (PLC_Link[0].ReadByte(DataType.DataBlock, 10080, 3) > 0)
                //{
                //    alarmNum = File.ReadAllLines(Application.StartupPath + "\\报警配置.txt", Encoding.UTF8);
                //    for (int i = 0; i < 8; i++)
                //    {
                //        if (PLC_Link[0].readBoolen("DB10080.DBX3." + i.ToString()))
                //        {
                //            //inAlarm("OA报警[1]夹紧气缸前进超时A"); 
                //            label242.Text = alarmNum[i + 8];
                //            break;
                //        }
                //    }
                //}
                else
                {
                    if (clear)
                    {
                        label242.Text = "";
                        clear = false;
                    }
                }
            }
            finally
            {

            }
        }


        #region 标签打印

        PrintDocument printDoc = new PrintDocument();//创建打印对象
        bool printA;
        bool printAok;
        bool printB;
        bool printBok;
        bool printC;
        bool printCok;
        bool printD;
        bool printDok;
        private void button9_Click(object sender, EventArgs e)
        {
            //if (Program.userlogin.UserID == 1 || Program.userlogin.UserID == 2)
            //{
            try
            {
                printLab(@"D:\print\" + print.biaoqianmuban, "OK print");       //23/11/15 OK与NG互换先生产使用,已改回，待验证
                printA = true;
                this.printDoc.Print();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc + "接收失败");
            }
            //}
            //else
            //{
            //    MessageBox.Show("权限不够，请呼叫班长！");
            //}

        }

        private void LotteryPrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            this.PrintLottery(e);
        }
        //计算一年中的第几天
        int days;
        public int GetDayNumberOfYear()
        {

            int year = System.DateTime.Now.Year;
            System.DateTime dt1 = new System.DateTime(year, 1, 1);
            days = (System.DateTime.Now.Date - dt1.Date).Days + 1;
            return days;
        }
        public void PrintLottery(System.Drawing.Printing.PrintPageEventArgs e)
        {
            //合格
            if (printA)
            {

                ////序列号补0
                //string temp;
                //if (5 - label13.Text.Length>0)
                //{
                //    string sn ="";
                //    for (int i = 0; i < 5 - label13.Text.Length; i++)
                //    {
                //        sn += 0;
                //    }
                //    temp = sn + label13.Text;
                //}
                //else
                //{
                //    temp = label13.Text;
                //}
                ////日期补0
                //days = GetDayNumberOfYear();
                //string temp1;
                //if (3 - days.ToString().Length > 0)
                //{
                //    string sn = "";
                //    for (int i = 0; i < 3 - days.ToString().Length; i++)
                //    {
                //        sn += 0;
                //    }
                //    temp1 = sn + days.ToString();
                //}
                //else
                //{
                //    temp1 = days.ToString();
                //}
                // neirong = "[>16" + print.lingjianhao +"V"+ print.banbenhao +"D"+ temp1+ System.DateTime.Now.ToString("yy") + print.AIdaima +"S"+ print.chanxianbanci+"N"+ temp;
                ////e.Graphics.DrawImage(getnew(getqrcode(neirong, 2), 1), new Point(10, 20));
                ////e.Graphics.DrawString(print.lingjianhao, font1, Brushes.Blue, 80, 10, new StringFormat());
                ////e.Graphics.DrawString(print.banbenhao, font1, Brushes.Blue, 80, 25, new StringFormat());
                ////e.Graphics.DrawString(temp1 + DateTime.Now.ToString("yy"), font, Brushes.Blue, 80, 40, new StringFormat());
                ////e.Graphics.DrawString(print.AIdaima, font, Brushes.Blue, 80, 55, new StringFormat());
                ////e.Graphics.DrawString(print.chanxianbanci, font, Brushes.Blue, 80, 70, new StringFormat());
                ////e.Graphics.DrawString(temp, font, Brushes.Blue, 80, 85, new StringFormat());
                ////Bitmap bitb = new Bitmap("标签图片.bmp");
                ////bitb = getnew(bitb, 0.15);
                ////e.Graphics.DrawImage(bitb, 140, 30);
                //printA = false;
                //printAok = true;
            }
            //op100以前工位不合格
            if (printB)
            {
                //Font font = new Font("黑体", 10, (FontStyle)Enum.Parse(typeof(FontStyle), "Bold"));//内容字体
                ////e.Graphics.DrawImage(getnew(getqrcode("AE" + DateTime.Now.ToString("yyyyMMddHHmmss"), 3), 1), new Point(20, 15));
                //e.Graphics.DrawString("OP" + _plcStruct.byte_4 + "0不合格", font, Brushes.Blue, 15, 20, new StringFormat());
                //e.Graphics.DrawString("时间：" + System.DateTime.Now.ToString("yyyyMMddHHmmss"), font, Brushes.Blue, 15, 45, new StringFormat());
                //printB = false;
                //printBok = true;
            }
            //op100不合格
            if (printC)
            {
                //Font font = new Font("黑体", 10, (FontStyle)Enum.Parse(typeof(FontStyle), "Bold"));//内容字体
                ////e.Graphics.DrawImage(getnew(getqrcode("AE" + DateTime.Now.ToString("yyyyMMddHHmmss"), 3), 1), new Point(20, 15));
                //e.Graphics.DrawString("OP100人工判定不合格", font, Brushes.Blue, 15, 20, new StringFormat());
                //e.Graphics.DrawString("时间：" + System.DateTime.Now.ToString("yyyyMMddHHmmss"), font, Brushes.Blue, 15, 45, new StringFormat());
                //printC = false;
                //printCok = true;
            }
            //手动打印
            if (printD)
            {

                //neirong = "[>16" + textBox1.Text + "V" + textBox2.Text + "D" + textBox5.Text + textBox3.Text + "S" + textBox4.Text + "N" + textBox6.Text;
                //e.Graphics.DrawImage(getnew(getqrcode(neirong, 2), 1), new Point(10, 20));
                //e.Graphics.DrawString(textBox1.Text, font1, Brushes.Blue, 80, 10, new StringFormat());
                //e.Graphics.DrawString(textBox2.Text, font1, Brushes.Blue, 80, 25, new StringFormat());
                //e.Graphics.DrawString(textBox5.Text, font, Brushes.Blue, 80, 40, new StringFormat());
                //e.Graphics.DrawString(textBox3.Text, font, Brushes.Blue, 80, 55, new StringFormat());
                //e.Graphics.DrawString(textBox4.Text, font, Brushes.Blue, 80, 70, new StringFormat());
                //e.Graphics.DrawString(textBox6.Text, font, Brushes.Blue, 80, 85, new StringFormat());
                //Bitmap bitb = new Bitmap("标签图片.bmp");
                //bitb = getnew(bitb, 0.15);
                //e.Graphics.DrawImage(bitb, 140, 30);
                //printD = false;
                //printDok = true;
            }
        }

        //合格打印
        string temp;
        string temp1;
        public void printLab(string labName, string strPrintName)
        {
            label28.Text = "生成打印内容";
            ApplicationClass lbl = new ApplicationClass();
            //序列号补0
            if (label2.Text.Contains("DIDI"))
            {
                if (4 - PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0).ToString().Length > 0)     //合格标签计数
                {
                    string sn = "";
                    for (int i = 0; i < 4 - PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0).ToString().Length; i++)
                    {
                        sn += 0;
                    }
                    if (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) >= 999)
                    {
                        PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, 0);
                    }
                    temp = sn + (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)));
                    PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) + 1);
                }
                else
                {
                    temp = (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) + 1).ToString();
                    PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) + 1);
                }
                temp = day + temp;
            }
            else
            {
                if (5 - PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0).ToString().Length > 0)     //合格标签计数
                {
                    string sn = "";
                    for (int i = 0; i < 5 - PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0).ToString().Length; i++)
                    {
                        sn += 0;
                    }
                    if (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) >= 999)
                    {
                        PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, 0);
                    }
                    temp = sn + (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)));
                    PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) + 1);
                }
                else
                {
                    temp = (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) + 1).ToString();
                    PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 0, VarType.DInt, 1, 0)) + 1);
                }
            }
            //日期补0
            //days = GetDayNumberOfYear();
            //string temp1;
            //if (3 - days.ToString().Length > 0)
            //{
            //    string sn = "";
            //    for (int i = 0; i < 3 - days.ToString().Length; i++)
            //    {
            //        sn += 0;
            //    }
            //    temp1 = sn + days.ToString();
            //}
            //else
            //{
            //    temp1 = days.ToString();
            //}
            //neirong = "[>16" + print.lingjianhao + "V" + print.banbenhao + "D" + temp1 + System.DateTime.Now.ToString("yy") + print.AIdaima + "S" + print.chanxianbanci + "N" + temp;
            //neirong = print.lingjianhao + print.AIdaima  + System.DateTime.Now.ToString("yy") + (Convert.ToInt32(System.DateTime.Now.ToString("MM")) > 9 ? System.DateTime.Now.ToString("MM").Equals("10") ? "A" : System.DateTime.Now.ToString("MM").Equals("11") ? "B" : System.DateTime.Now.ToString("MM").Equals("12") ? "C" : "" : Convert.ToInt32(System.DateTime.Now.ToString("MM")).ToString()) + System.DateTime.Now.ToString("dd") + temp;
            if (label2.Text.Contains("DIDI"))
            { 
                neirong =  print.lingjianhao + print.AIdaima +  temp + Fxnumber;
            }
            else
            {
                neirong = print.banbenhao + "#" +  print.AIdaima + "#" + print.chanxianbanci + "#" + System.DateTime.Now.ToString("yyyy") + System.DateTime.Now.ToString("MM") + System.DateTime.Now.ToString("dd") + temp;         //23/11/15年份改为四位数的年份
            }
            try
            {
                lbl.Documents.Open(labName, false);
                Document doc = lbl.ActiveDocument;
                doc.Printer.SwitchTo(strPrintName, "", true);
                doc.Variables.FreeVariables.Item("变量0").Value = neirong;
                doc.Variables.FreeVariables.Item("变量1").Value = print.lingjianhao;   //lingjianhao 8105100DM1
                doc.Variables.FreeVariables.Item("变量2").Value = label2.Text.Contains("DIDI") ? Fxnumber :print.banbenhao;        //DIDI变量2为返修次数
                //doc.Variables.FreeVariables.Item("变量3").Value = System.DateTime.Now.ToString("yy")+ 0 + (Convert.ToInt32(System.DateTime.Now.ToString("MM"))>9? System.DateTime.Now.ToString("MM").Equals("10")?"A": System.DateTime.Now.ToString("MM").Equals("11") ?"B": System.DateTime.Now.ToString("MM").Equals("12") ?"C":"": Convert.ToInt32(System.DateTime.Now.ToString("MM")).ToString()) + System.DateTime.Now.ToString("dd")+ temp;
                //doc.Variables.FreeVariables.Item("变量3").Value = System.DateTime.Now.ToString("yy") + System.DateTime.Now.ToString("MM") + System.DateTime.Now.ToString("dd") + temp;
                doc.Variables.FreeVariables.Item("变量3").Value = label2.Text.Contains("DIDI")? temp : (System.DateTime.Now.ToString("yyyy") + System.DateTime.Now.ToString("MM") + System.DateTime.Now.ToString("dd") + temp);
                doc.Variables.FreeVariables.Item("变量4").Value = print.AIdaima;      //供应商代码 101170
                doc.Variables.FreeVariables.Item("变量5").Value = print.chanxianbanci;
                //doc.Variables.FreeVariables.Item("变量6").Value = temp;
                //doc.Variables.FreeVariables.Item("日期0").Value = System.DateTime.Now.ToString("yy/MM/dd/ 
                doc.PrintDocument(1);
                printA = false;
                printAok = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                lbl.Documents.CloseAll(true);
                lbl.Quit();
                GC.Collect(0);
            }

        }
        //NG(不合格)打印
        public void NGprintLab(string labName, string strPrintName, string NGresult)
         {
            label28.Text = "生成不合格打印内容";
            ApplicationClass lbl = new ApplicationClass();
            //序列号补0
            if (5 - PLC_Link[0].plc.Read(DataType.DataBlock, 101, 4, VarType.DInt, 1, 0).ToString().Length > 0)      //不合格标签计数
            {
                string sn = "";
                for (int i = 0; i < 5 - PLC_Link[0].plc.Read(DataType.DataBlock, 101, 4, VarType.DInt, 1, 0).ToString().Length; i++)
                {
                    sn += 0;
                }
                if (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 4, VarType.DInt, 1, 0)) >= 999)
                {
                    PLC_Link[0].plc.Write(DataType.DataBlock, 101, 4, 0);
                }
                temp1 = sn + (Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 4, VarType.DInt, 1, 0)) + 1);
                PLC_Link[0].plc.Write(DataType.DataBlock, 101, 4, Convert.ToInt32(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 4, VarType.DInt, 1, 0)) + 1);
                //label16.Text = temp1;
            }
            else
            {
                temp1 = (Convert.ToInt16(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 4, VarType.Int, 1, 0)) + 1).ToString();
                PLC_Link[0].plc.Write(DataType.DataBlock, 101, 4, Convert.ToInt16(PLC_Link[0].plc.Read(DataType.DataBlock, 101, 4, VarType.Int, 1, 0)) + 1);
            }
            string month = System.DateTime.Now.Month.ToString();
            if (month.Length < 2)
            {
                month = "0" + month;
            }
            string YMD = month;
            string day = System.DateTime.Now.Day.ToString();
            if (day.Length < 2)
            {
                day = "0" + day;
            }
            YMD = System.DateTime.Now.Year.ToString().Substring(2, 2) + YMD + day;
            neirong = "DIDIR1" + YMD + temp1;
            string SN = "DIDI" + YMD + temp1;
            string times = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            //label16.Text = neirong;
            try
            {
                lbl.Documents.Open(labName, false);
                Document doc = lbl.ActiveDocument;
                doc.Printer.SwitchTo(strPrintName, "", true);
                doc.Variables.FreeVariables.Item("变量0").Value = SN;
                doc.Variables.FreeVariables.Item("变量1").Value = times;
                doc.Variables.FreeVariables.Item("变量2").Value = neirong;
                doc.Variables.FreeVariables.Item("变量3").Value = "DIDI";
                doc.Variables.FreeVariables.Item("变量4").Value = NGresult;
                doc.PrintDocument(1);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                lbl.Documents.CloseAll(true);
                lbl.Quit();
                GC.Collect(0);
            }

        }
        #endregion

        private void button10_Click(object sender, EventArgs e)
        {
            //if (Program.userlogin.UserID == 1 || Program.userlogin.UserID == 2)
            //{
            //string ng = "";
            //try
            //{
            //    string sql = "select [不合格信息] from productData where ID='{0}'";
            //    sql = string.Format(sql, ID);
            //    SqlDataReader objReader = DBHelper.GetReader(sql);
            //    while (objReader.Read())
            //    {
            //        ng = objReader["不合格信息"].ToString();   //DIDI没有录入不合格信息
            //    }
            //    objReader.Close();
            //}
            //catch (Exception ex1)
            //{
            //    MessageBox.Show(ex1.ToString(), "连接数据库失败");
            //}
            //NGprintLab(@"D:\printNG\X01不合格标签.lab", "Argox DX-4200 PPLB", "OP" + _plcStruct.byte_4 + "不合格：" + ng.Replace("rn", "\r\n"));
            //printBok = true;
            NGprintLab(@"D:\printNG\DIDI不合格标签.lab", "NG print", "OP" + _plcStruct.byte_4 + "不合格：" /*+ ng.Replace("rn", "\r\n")*/);          //23/11/15 OK与NG互换先生产使用,已改回，待验证
            //printLab(@"D:\printNG\" + "DIDI不合格标签.lab", "ZDesigner ZT411-300dpi ZPL (副本 2)");
            printDoc.DefaultPageSettings.PrinterSettings.PrinterName = "NG print";
            printBok = true;
            this.printDoc.Print();
            //}
            //else
            //{
            //    MessageBox.Show("权限不够，请呼叫班长！");
            //}
        }

        //private void button11_Click(object sender, EventArgs e)
        //{
        //    PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 532, 1, 1);
        //}
        //人工判断不合格
        private void button11_MouseDown(object sender, MouseEventArgs e)
        {
            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 532, 1, 1);
        }
        private void button11_MouseUp(object sender, MouseEventArgs e)
        {
            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 532, 1, 0);
        }

        //call the monitor
        int secondCount;
        int secondCount1;
        System.Timers.Timer timer = new System.Timers.Timer();
        System.Timers.Timer timercall = new System.Timers.Timer();
        private string yesterday;
        private string strfile;

        private void button7_Click(object sender, EventArgs e)
        {
            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 618, 6, !Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 6)));
            if (Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 6)))
            {
                timer.Start();
                secondCount = 0;
            }
            if (Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 6)) == false)
            {
                timer.Stop();

                string sql = "insert into calRecord([callStation],[callOP],[callOptions],[callTimers],[callDateTime]) values('{0}','{1}','{2}','{3}','{4}')";
                sql = string.Format(sql, "OP130", Program.userlogin.Admin, "呼叫班长", secondCount, System.DateTime.Now.ToString());
                num1 = SQLHelp.AddData(sql);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 618, 7, !Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 7)));
            if (Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 7)))
            {
                timercall.Start();
                secondCount1 = 0;
            }
            if (Convert.ToBoolean(PLC_Link[0].plc.Read(DataType.DataBlock, 99, 618, VarType.Bit, 1, 7)) == false)
            {
                timercall.Stop();

                string sql = "insert into calRecord([callStation],[callOP],[callOptions],[callTimers],[callDateTime]) values('{0}','{1}','{2}','{3}','{4}')";
                sql = string.Format(sql, "OP90", Program.userlogin.Admin, "呼叫物料", secondCount1, System.DateTime.Now.ToString());
                num1 = SQLHelp.AddData(sql);
            }
        }
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            secondCount++;
            timer.Start();
        }
        void timercall_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            secondCount1++;
            timercall.Start();
        }
        public void GetFileNames(ref List<string> FileNames)
        {
            string ext = ".lab";

            DirectoryInfo theFolder = new DirectoryInfo(@"d:\print\");
            foreach (FileInfo file in theFolder.GetFiles())
            {
                if (file.Extension.ToUpper() == ext.ToUpper())
                {
                    FileNames.Add(file.FullName.Substring(file.FullName.LastIndexOf("\\") + 1, file.FullName.Length - 1 - file.FullName.LastIndexOf("\\")));

                }
            }

        }

        

        private void button2_Click(object sender, EventArgs e)
        {
            //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 3, 1);
        }

        private void button9_MouseDown(object sender, MouseEventArgs e)
        {
            button9.BackColor = Color.Green;
        }
        private void button9_MouseUp(object sender, MouseEventArgs e)
        {
            button9.BackColor = Color.Silver;
        }

        private void button10_MouseDown(object sender, MouseEventArgs e)
        {
            button10.BackColor = Color.Green;
        }
        private void button10_MouseUp(object sender, MouseEventArgs e)
        {
            button10.BackColor = Color.Silver;
        }
        public class ScanerHook
        {
            public delegate void ScanerDelegate(ScanerCodes codes);
            public event ScanerDelegate ScanerEvent;
            delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
            private int hKeyboardHook = 0;
            private ScanerCodes codes = new ScanerCodes();
            private HookProc hookproc;
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            private static extern bool UnhookWindowsHookEx(int idHook);
            [DllImport("user32", EntryPoint = "GetKeyNameText")]
            private static extern int GetKeyNameText(int IParam, StringBuilder lpBuffer, int nSize);
            [DllImport("user32", EntryPoint = "GetKeyboardState")]
            private static extern int GetKeyboardState(byte[] pbKeyState);
            [DllImport("user32", EntryPoint = "ToAscii")]
            private static extern bool ToAscii(int VirtualKey, int ScanCode, byte[] lpKeySate, ref uint lpChar, int uFlags);
            [DllImport("kernel32.dll")]
            public static extern IntPtr GetModuleHandle(string name);
            public ScanerHook()
            {
            }
            public bool Start()
            {
                if (hKeyboardHook == 0)
                {
                    hookproc = new HookProc(KeyboardHookProc);
                    //GetModuleHandle 函数 替代 Marshal.GetHINSTANCE
                    //防止在 framework4.0中 注册钩子不成功
                    IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
                    //WH_KEYBOARD_LL=13
                    //全局钩子 WH_KEYBOARD_LL
                    //  hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
                    hKeyboardHook = SetWindowsHookEx(13, hookproc, modulePtr, 0);
                }
                return (hKeyboardHook != 0);
            }
            public bool Stop()
            {
                if (hKeyboardHook != 0)
                {
                    return UnhookWindowsHookEx(hKeyboardHook);
                }
                return true;
            }
            private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
            {
                EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
                codes.Add(msg);
                if (ScanerEvent != null && msg.message == 13 && msg.paramH > 0 && !string.IsNullOrEmpty(codes.Result))
                {
                    ScanerEvent(codes);
                }
                return 0;
            }
            public class ScanerCodes
            {
                private int ts = 300; // 指定输入间隔为300毫秒以内时为连续输入
                private List<List<EventMsg>> _keys = new List<List<EventMsg>>();
                private List<int> _keydown = new List<int>();   // 保存组合键状态
                private List<string> _result = new List<string>();  // 返回结果集
                private System.DateTime _last = System.DateTime.Now;
                private byte[] _state = new byte[256];
                private string _key = string.Empty;
                private string _cur = string.Empty;
                public EventMsg Event
                {
                    get
                    {
                        if (_keys.Count == 0)
                        {
                            return new EventMsg();
                        }
                        else
                        {
                            return _keys[_keys.Count - 1][_keys[_keys.Count - 1].Count - 1];
                        }
                    }
                }
                public List<int> KeyDowns
                {
                    get
                    {
                        return _keydown;
                    }
                }
                public System.DateTime LastInput
                {
                    get
                    {
                        return _last;
                    }
                }
                public byte[] KeyboardState
                {
                    get
                    {
                        return _state;
                    }
                }
                public int KeyDownCount
                {
                    get
                    {
                        return _keydown.Count;
                    }
                }
                public string Result
                {
                    get
                    {
                        if (_result.Count > 0)
                        {
                            return _result[_result.Count - 1].Trim();
                        }
                        else
                        {
                            return null;
                        }
                    }
                }
                public string CurrentKey
                {
                    get
                    {
                        return _key;
                    }
                }
                public string CurrentChar
                {
                    get
                    {
                        return _cur;
                    }
                }
                public bool isShift
                {
                    get
                    {
                        return _keydown.Contains(160);
                    }
                }
                public void Add(EventMsg msg)
                {
                    #region 记录按键信息
                    // 首次按下按键
                    if (_keys.Count == 0)
                    {
                        _keys.Add(new List<EventMsg>());
                        _keys[0].Add(msg);
                        _result.Add(string.Empty);
                    }
                    // 未释放其他按键时按下按键
                    else if (_keydown.Count > 0)
                    {
                        _keys[_keys.Count - 1].Add(msg);
                    }
                    // 单位时间内按下按键
                    else if (((TimeSpan)(System.DateTime.Now - _last)).TotalMilliseconds < ts)
                    {
                        _keys[_keys.Count - 1].Add(msg);
                    }
                    // 从新记录输入内容
                    else
                    {
                        _keys.Add(new List<EventMsg>());
                        _keys[_keys.Count - 1].Add(msg);
                        _result.Add(string.Empty);
                    }
                    #endregion
                    _last = System.DateTime.Now;
                    #region 获取键盘状态
                    // 记录正在按下的按键
                    if (msg.paramH == 0 && !_keydown.Contains(msg.message))
                    {
                        _keydown.Add(msg.message);
                    }
                    // 清除已松开的按键
                    if (msg.paramH > 0 && _keydown.Contains(msg.message))
                    {
                        _keydown.Remove(msg.message);
                    }
                    #endregion
                    #region 计算按键信息
                    int v = msg.message & 0xff;
                    int c = msg.paramL & 0xff;
                    StringBuilder strKeyName = new StringBuilder(500);
                    if (GetKeyNameText(c * 65536, strKeyName, 255) > 0)
                    {
                        _key = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
                        GetKeyboardState(_state);
                        if (_key.Length == 1 && msg.paramH == 0)
                        {
                            // 根据键盘状态和shift缓存判断输出字符
                            _cur = ShiftChar(_key, isShift, _state).ToString();
                            _result[_result.Count - 1] += _cur;
                        }
                        else
                        {
                            _cur = string.Empty;
                        }
                    }
                    #endregion
                }
                private char ShiftChar(string k, bool isShiftDown, byte[] state)
                {
                    bool capslock = state[0x14] == 1;
                    bool numlock = state[0x90] == 1;
                    bool scrolllock = state[0x91] == 1;
                    bool shiftdown = state[0xa0] == 1;
                    char chr = (capslock ? k.ToUpper() : k.ToLower()).ToCharArray()[0];
                    if (isShiftDown)
                    {
                        if (chr >= 'a' && chr <= 'z')
                        {
                            chr = (char)((int)chr - 32);
                        }
                        else if (chr >= 'A' && chr <= 'Z')
                        {
                            chr = (char)((int)chr + 32);
                        }
                        else
                        {
                            string s = "`1234567890-=[];',./";
                            string u = "~!@#$%^&*()_+{}:\"<>?";
                            if (s.IndexOf(chr) >= 0)
                            {
                                return (u.ToCharArray())[s.IndexOf(chr)];
                            }
                        }
                    }
                    return chr;
                }
            }
            public struct EventMsg
            {
                public int message;
                public int paramL;
                public int paramH;
                public int Time;
                public int hwnd;
            }
        }

        private void Listener_ScanerEvent(ScanerHook.ScanerCodes codes)
        {
            textBox9.Text = codes.Result;
            #region 查询总成码是否重复
            string sql = "select [总成码] from productData where [总成码] = '" + textBox9.Text + "'";
            SqlDataReader objReader = SQLHelp.GetReader(sql);
            int temp2 = 0;
            while (objReader.Read())
            {
                temp2 = 1;
                label28.Text = "条码重复";
            }
            objReader.Close();
            #endregion
            if (textBox9.Text.Equals(neirong) && temp2 == 0 /*&& textBox9.Text.Length == 40*/ && temp.Length == 5)
            {
                textBox9.BackColor = System.Drawing.Color.Green;
                PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 0, 1);
            }
            else
            {
                textBox9.BackColor = System.Drawing.Color.Red;
                PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 240, 1, 1);
                if (textBox9.Text.Length != 40)
                {
                    label28.Text = "条码位数不正确,请点击合格标签单张打印按钮！";
                }
            }
        }

        //手动模式
        private void button12_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX0.1", true);
        }
        private void button12_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX0.1", false);
            if ((Program.userlogin.UserID == 1) || (Program.userlogin.UserID == 2))      //登录账户有操作权限
            {
                OpenForm(new FormManMode());
            }
            else    //进行登录操作
            {
                MessageBox.Show("没有操作权限", "提示！");
                return;
            }
        }
        //自动模式
        private void button6_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX0.0", true);
            CloseForm();
        }
        private void button6_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX0.0", false);
            CloseForm();
        }
        //报警复位
        private void button5_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX1.2", true);
        }
        private void button5_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX1.2", false);
        }
        //返回原位（大复位）
        private void button13_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX1.1", true);
        }
        private void button13_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB10050.DBX1.1", false);
        }
        
    }
}
